import fs from 'fs'
const BASE_URL = './database'

/**
 * @description 创建文件夹
 * @param {String} folderName
 */
export const createFolder = (folderName) => {
	return new Promise((resolve, reject) => {
		fs.mkdir(`./${folderName}`, (err) => {
			if (err) reject(err);
			resolve(true);
		});
	})
}

/**
 * @description 判断文件是否存在
 * @param {String} fileName 
 */
export const folderExists = (fileName) => {
	return new Promise((resolve, reject) => {
		try {
			const exist = fs.existsSync(fileName)
			resolve(exist)

		} catch (err) {
			reject(err)
		}

	})
}

/**
 * @description 创建文件
 * @param {String} fileName 
 * @param {Object | Array} content 
 */
export const createFile = (fileName, content) => {
	return new Promise((resolve, reject) => {
		let file = JSON.stringify(content, null, '\t');
		fs.writeFile(`${BASE_URL}/${fileName}.json`, file, (err) => {
			if (err) reject(err)
			resolve(true)
		})
	})
}

/**
 * @description 删除文件
 * @param {String} fileName 
 */
export const deleteFile = (fileName) => {
	return new Promise((resolve, reject) => {
		fs.unlink(`${BASE_URL}/${fileName}.json`, (err) => {
			if (err) reject(err)
			resolve(true)
		})
	})
}

/**
 * @description 读取文件
 * @param {String} fileName 
 */
export const readFile = (fileName) => {
	return new Promise((resolve, reject) => {
		try {
			const data = fs.readFileSync(`${BASE_URL}/${fileName}.json`);
			resolve(JSON.parse(data))
		} catch (err) {
			reject(err)
		}
	})
}

/**
 * @description 写入文件
 * @param {String} fileName 
 * @param {Object | Array} newContent 
 */
export const writeFile = (fileName, newContent) => {
	return new Promise((resolve, reject) => {
		try {
			const file = JSON.stringify(newContent, null, '\t');
			fs.writeFileSync(`${BASE_URL}/${fileName}.json`, file);
			resolve(true)
		} catch (err) {
			reject(err)
		}
	})
}